<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="此为龙果学院课程笔记，记录以供以后翻看 Redis企业应用实战上一篇说了redis的持久化的原理和操作，但是在企业中，持久化到底是怎么去用得呢？企业级的数据备份和各种灾难下的数据恢复，是怎么做的呢？ 企业级的持久化的配置策略在企业中，RDB的生成策略，用默认的配置也差不多。 save 60 10000：如果你希望尽可能确保，RDB最多丢1分钟的数据，那么尽量就是每隔1分钟都生成一个快照，但是低峰期">
<meta name="keywords" content="redis">
<meta property="og:type" content="article">
<meta property="og:title" content="高可用缓存架构实战2-Redis企业级应用实战">
<meta property="og:url" content="http://www.saily.top/2018/02/12/cache02/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="此为龙果学院课程笔记，记录以供以后翻看 Redis企业应用实战上一篇说了redis的持久化的原理和操作，但是在企业中，持久化到底是怎么去用得呢？企业级的数据备份和各种灾难下的数据恢复，是怎么做的呢？ 企业级的持久化的配置策略在企业中，RDB的生成策略，用默认的配置也差不多。 save 60 10000：如果你希望尽可能确保，RDB最多丢1分钟的数据，那么尽量就是每隔1分钟都生成一个快照，但是低峰期">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://images2015.cnblogs.com/blog/631180/201603/631180-20160310114352444-1976154985.png">
<meta property="og:image" content="https://images2015.cnblogs.com/blog/631180/201603/631180-20160310164439163-353212676.png">
<meta property="og:updated_time" content="2018-08-25T07:18:10.225Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="高可用缓存架构实战2-Redis企业级应用实战">
<meta name="twitter:description" content="此为龙果学院课程笔记，记录以供以后翻看 Redis企业应用实战上一篇说了redis的持久化的原理和操作，但是在企业中，持久化到底是怎么去用得呢？企业级的数据备份和各种灾难下的数据恢复，是怎么做的呢？ 企业级的持久化的配置策略在企业中，RDB的生成策略，用默认的配置也差不多。 save 60 10000：如果你希望尽可能确保，RDB最多丢1分钟的数据，那么尽量就是每隔1分钟都生成一个快照，但是低峰期">
<meta name="twitter:image" content="https://images2015.cnblogs.com/blog/631180/201603/631180-20160310114352444-1976154985.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/02/12/cache02/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>高可用缓存架构实战2-Redis企业级应用实战 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/02/12/cache02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">高可用缓存架构实战2-Redis企业级应用实战
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-12T17:27:23+08:00">2月 12 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/高可用缓存架构实战/" itemprop="url" rel="index"><span itemprop="name">高可用缓存架构实战</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>此为龙果学院课程笔记，记录以供以后翻看</p>
<h1 id="Redis企业应用实战"><a href="#Redis企业应用实战" class="headerlink" title="Redis企业应用实战"></a>Redis企业应用实战</h1><p>上一篇说了redis的持久化的原理和操作，但是在企业中，持久化到底是怎么去用得呢？企业级的数据备份和各种灾难下的数据恢复，是怎么做的呢？</p>
<h2 id="企业级的持久化的配置策略"><a href="#企业级的持久化的配置策略" class="headerlink" title="企业级的持久化的配置策略"></a>企业级的持久化的配置策略</h2><p>在企业中，RDB的生成策略，用默认的配置也差不多。</p>
<p><code>save 60 10000</code>：如果你希望尽可能确保，RDB最多丢1分钟的数据，那么尽量就是每隔1分钟都生成一个快照，但是低峰期数据量很少，也没必要这样设置。</p>
<p>10000-&gt;生成RDB，1000-&gt;RDB，这个根据你自己的应用和业务的数据量，你自己去决定。</p>
<p>AOF一定要打开，fsync配置，everysec</p>
<p><code>auto-aof-rewrite-percentage 100</code>: 就是当前AOF大小膨胀到超过上次100%，上次的两倍就重写。<br><code>auto-aof-rewrite-min-size 64mb</code>: 至少64m才重写，根据你的数据量来定，16mb，32mb。</p>
<a id="more"></a>
<h2 id="企业级的数据备份方案"><a href="#企业级的数据备份方案" class="headerlink" title="企业级的数据备份方案"></a>企业级的数据备份方案</h2><p>RDB非常适合做冷备，每次生成之后，就不会再有修改了</p>
<p>数据备份方案：</p>
<ol>
<li>写crontab定时调度脚本去做数据备份</li>
<li>每小时都copy一份rdb的备份，到一个目录中去，仅仅保留最近48小时的备份</li>
<li>每天都保留一份当日的rdb的备份，到一个目录中去，仅仅保留最近1个月的备份</li>
<li>每次copy备份的时候，都把太旧的备份给删了</li>
<li>每天晚上将当前服务器上所有的数据备份，发送一份到远程的云服务上去</li>
</ol>
<p>创建一个备份目录：<code>/usr/local/redis</code>，下面的脚本基于这个目录做备份。</p>
<h3 id="每小时copy一次备份，删除48小时前的数据"><a href="#每小时copy一次备份，删除48小时前的数据" class="headerlink" title="每小时copy一次备份，删除48小时前的数据"></a>每小时copy一次备份，删除48小时前的数据</h3><p>redis_rdb_copy_hourly.sh</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh </span></span><br><span class="line"></span><br><span class="line">cur_date=`date +%Y%m%d%H`</span><br><span class="line">rm -rf /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line">mkdir /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line">cp /var/redis/6379/dump.rdb /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line"></span><br><span class="line">del_date=`date -d -48hour +%Y%m%d%H`</span><br><span class="line">rm -rf /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$del_date</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">chmod 777 redis_rdb_copy_hourly.sh</span><br><span class="line">crontab -e</span><br><span class="line">0 * * * * sh /usr/<span class="built_in">local</span>/redis/copy/redis_rdb_copy_hourly.sh</span><br></pre></td></tr></table></figure>
<h3 id="每天copy一次备份"><a href="#每天copy一次备份" class="headerlink" title="每天copy一次备份"></a>每天copy一次备份</h3><p>redis_rdb_copy_daily.sh</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh </span></span><br><span class="line"></span><br><span class="line">cur_date=`date +%Y%m%d`</span><br><span class="line">rm -rf /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line">mkdir /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line">cp /var/redis/6379/dump.rdb /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$cur_date</span></span><br><span class="line"></span><br><span class="line">del_date=`date -d -1month +%Y%m%d`</span><br><span class="line">rm -rf /usr/<span class="built_in">local</span>/redis/snapshotting/<span class="variable">$del_date</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">chmod 777 redis_rdb_copy_daily.sh</span><br><span class="line">crontab -e</span><br><span class="line">0 0 * * * sh /usr/<span class="built_in">local</span>/redis/copy/redis_rdb_copy_daily.sh</span><br></pre></td></tr></table></figure>
<h3 id="数据恢复方案"><a href="#数据恢复方案" class="headerlink" title="数据恢复方案"></a>数据恢复方案</h3><ol>
<li>如果是redis进程挂掉，那么重启redis进程即可，直接基于AOF日志文件恢复数据，上一篇文章在AOF数据恢复那一块说过了，<code>fsync everysec</code>，最多就丢一秒的数据。</li>
</ol>
<ol start="2">
<li><p>如果是redis进程所在机器挂掉，那么重启机器后，尝试重启redis进程，尝试直接基于AOF日志文件进行数据恢复</p>
<blockquote>
<p>AOF没有破损，也是可以直接基于AOF恢复的。</p>
</blockquote>
<blockquote>
<p>AOF append-only，顺序写入，如果AOF文件破损，那么用redis-check-aof fix</p>
</blockquote>
</li>
<li><p>如果redis当前最新的AOF和RDB文件出现了丢失/损坏，那么可以尝试基于该机器上当前的某个最新的RDB数据副本进行数据恢复，当前最新的AOF和RDB文件都出现了丢失/损坏到无法恢复，一般不是机器的故障，人为（不小心被删除）。</p>
<blockquote>
<p>找到RDB最新的一份备份，小时级的备份可以了，小时级的肯定是最新的，copy到redis里面去，就可以恢复到某一个小时的数据（注意如果存在<code>appendonly.aof</code>文件，会优先读取<code>appendonly.aof</code>文件）        </p>
</blockquote>
<blockquote>
<p>虽然你删除了appendonly.aof，但是因为打开了aof持久化，redis就一定会优先基于aof去恢复，即使文件不在，那就创建一个新的空的aof文件。正确的操作如下：停止redis，关闭aof，拷贝rdb备份，重启redis，确认数据恢复，直接在命令行热修改redis配置，打开aof，这个时候redis就会将内存中的数据对应的日志，写入aof文件中。此时aof和rdb两份数据文件的数据就同步了，在redis-cli中执行<code>config set appendonly yes</code>热修改配置参数，但是这个时候配置文件中的实际的参数没有被修改，再次停止redis，手动修改配置文件，打开aof的命令，再次重启redis。</p>
</blockquote>
</li>
<li><p>如果当前机器上的所有RDB文件全部损坏，那么从远程的云服务上拉取最新的RDB快照回来恢复数据</p>
</li>
<li><p>如果是发现有重大的数据错误，比如某个小时上线的程序一下子将数据全部污染了，数据全错了，那么可以选择某个更早的时间点，对数据进行恢复。</p>
</li>
</ol>
<h2 id="如何通过读写分离来承载读请求QPS超过10万-？"><a href="#如何通过读写分离来承载读请求QPS超过10万-？" class="headerlink" title="如何通过读写分离来承载读请求QPS超过10万+？"></a>如何通过读写分离来承载读请求QPS超过10万+？</h2><h3 id="redis高并发跟整个系统的高并发之间的关系"><a href="#redis高并发跟整个系统的高并发之间的关系" class="headerlink" title="redis高并发跟整个系统的高并发之间的关系"></a>redis高并发跟整个系统的高并发之间的关系</h3><p>做高并发的话，不可避免的是需要把底层的缓存搞得很好。如果是用mysql来做高并发，即时做到了，那么也是通过一系列复杂的分库分表，而且mysql高并发一般用在订单系统，事务要求比较高的地方，QPS能到几万，就已经比较高了。</p>
<p>但是如果要做一些电商的商品详情页，真正的超高并发，QPS上十万，甚至是百万，一秒钟百万的请求量，光是redis是不够的，但是redis是整个大型的缓存架构、支撑高并发的架构中，非常重要的一个环节。</p>
<p>首先，底层的缓存中间件，缓存系统，必须能够支撑的起我们说的那种高并发，其次，再经过良好的整体的缓存架构的设计（多级缓存架构、热点缓存），支撑真正的上十万，甚至上百万的高并发。</p>
<h3 id="redis不能支撑高并发的瓶颈在哪里？"><a href="#redis不能支撑高并发的瓶颈在哪里？" class="headerlink" title="redis不能支撑高并发的瓶颈在哪里？"></a>redis不能支撑高并发的瓶颈在哪里？</h3><p>单机是不能支撑高并发的，单机能够承载的QPS大概在上万或者几万不等，根据业务复杂度决定。</p>
<h3 id="如果redis要支撑超过10万-的并发，那应该怎么做？"><a href="#如果redis要支撑超过10万-的并发，那应该怎么做？" class="headerlink" title="如果redis要支撑超过10万+的并发，那应该怎么做？"></a>如果redis要支撑超过10万+的并发，那应该怎么做？</h3><p>单机的redis几乎不太可能说QPS超过10万+，除非一些特殊情况，比如你的机器性能特别好，配置特别高，物理机，维护做的特别好，而且你的整体的操作不是太复杂。</p>
<p><strong>读写分离</strong>，一般都是用来支撑<strong>读高并发</strong>的，写的请求是比较少的，可能写请求也就一秒钟几千，一两千，大量的请求都是读，一秒钟二十万次读。</p>
<p>读写分离：</p>
<pre><code>主从架构 -&gt; 读写分离 -&gt; 支撑10万+读QPS的架构
</code></pre><p>架构做成主从架构，一主多从，主负责写，并且将数据同步复制到其他的slave节点，从节点负责读，所有的读请求全部走从节点。</p>
<h3 id="Redis-Replication"><a href="#Redis-Replication" class="headerlink" title="Redis Replication"></a>Redis Replication</h3><p><img src="https://images2015.cnblogs.com/blog/631180/201603/631180-20160310114352444-1976154985.png" alt=""></p>
<p>Redis 支持简单且易用的主从复制（master-slave replication）功能，当主Redis服务器更新数据时能将数据同步到从Redis服务器。</p>
<h4 id="Redis-Replication的核心机制"><a href="#Redis-Replication的核心机制" class="headerlink" title="Redis Replication的核心机制"></a>Redis Replication的核心机制</h4><ol>
<li>redis采用异步方式复制数据到slave节点，不过redis 2.8开始，slave node会周期性地确认自己每次复制的数据量</li>
<li>一个master node是可以配置多个slave node的</li>
<li>slave node也可以连接其他的slave node</li>
<li>slave node做复制的时候，是不会block master node的正常工作的</li>
<li>slave node在做复制的时候，也不会block对自己的查询操作，它会用旧的数据集来提供服务; 但是复制完成的时候，需要删除旧数据集，加载新数据集，这个时候就会暂停对外服务了</li>
<li>slave node主要用来进行横向扩容，做读写分离，扩容的slave node可以提高读的吞吐量</li>
</ol>
<h5 id="master持久化对于主从架构的安全保障的意义"><a href="#master持久化对于主从架构的安全保障的意义" class="headerlink" title="master持久化对于主从架构的安全保障的意义"></a>master持久化对于主从架构的安全保障的意义</h5><p>如果采用了主从架构，那么必须开启master node的持久化。不建议用slave node作为master node的数据热备，因为那样的话，如果你关掉master的持久化，可能在master宕机重启的时候数据是空的，然后可能一经过复制，salve node数据也丢了。</p>
<pre><code>master -&gt; RDB和AOF都关闭了 -&gt; 全部在内存中
</code></pre><p>master宕机，重启，是没有本地数据可以恢复的，然后就会直接认为自己的数据是空的，master就会将空的数据集同步到slave上去，所有slave的数据全部清空，100%的数据丢失，所以master节点必须要使用持久化机制。</p>
<h5 id="主从架构的核心原理"><a href="#主从架构的核心原理" class="headerlink" title="主从架构的核心原理"></a>主从架构的核心原理</h5><p><img src="https://images2015.cnblogs.com/blog/631180/201603/631180-20160310164439163-353212676.png" alt=""></p>
<ul>
<li><p>当启动一个slave node的时候，它会发送一个PSYNC命令给master node</p>
</li>
<li><p>如果这时slave node重新连接master node，那么master node仅仅会复制给slave部分缺少的数据; 否则如果是slave node第一次连接master node，那么会触发一次full resynchronization</p>
</li>
<li><p>开始full resynchronization的时候，master会启动一个后台线程，开始生成一份RDB快照文件，同时还会将从客户端收到的所有写命令缓存在内存中。RDB文件生成完毕之后，master会将这个RDB发送给slave，slave会先写入本地磁盘，然后再从本地磁盘加载到内存中。然后master会将内存中缓存的写命令发送给slave，slave也会同步这些数据。</p>
</li>
<li><p>slave node如果跟master node有网络故障，断开了连接，会自动重连。master如果发现有多个slave node都来重新连接，仅仅会启动一个rdb save操作，用一份数据服务所有slave node。</p>
</li>
</ul>
<h5 id="主从复制的断点续传"><a href="#主从复制的断点续传" class="headerlink" title="主从复制的断点续传"></a>主从复制的断点续传</h5><p>从redis 2.8开始，就支持主从复制的断点续传，如果主从复制过程中，网络连接断掉了，那么可以接着上次复制的地方，继续复制下去，而不是从头开始复制一份。</p>
<p>master node会在内存中常见一个backlog，master和slave都会保存一个<code>replica offset</code>还有一个master id，offset就是保存在backlog中的。如果master和slave网络连接断掉了，slave会让master从上次的replica offset开始继续复制</p>
<p>但是如果没有找到对应的offset，那么就会执行一次<code>full resynchronization</code></p>
<h5 id="无磁盘化复制"><a href="#无磁盘化复制" class="headerlink" title="无磁盘化复制"></a>无磁盘化复制</h5><pre><code>repl-diskless-sync no
</code></pre><p>master在内存中直接创建rdb，然后发送给slave，不会在自己本地落地磁盘了</p>
<pre><code>repl-diskless-sync-delay 5
</code></pre><p>会等待一定时长（上面是5秒）再开始复制，因为要等更多slave重新连接过来。</p>
<h5 id="过期key处理"><a href="#过期key处理" class="headerlink" title="过期key处理"></a>过期key处理</h5><p>slave不会过期key，只会等待master过期key。如果master过期了一个key，或者通过LRU淘汰了一个key，那么会模拟一条del命令发送给slave。</p>
<h4 id="深入理解复制机制"><a href="#深入理解复制机制" class="headerlink" title="深入理解复制机制"></a>深入理解复制机制</h4><p>再次深入了解一下Redis的配置和复制机制。</p>
<h5 id="复制的完整流程"><a href="#复制的完整流程" class="headerlink" title="复制的完整流程"></a>复制的完整流程</h5><ol>
<li><p>slave node启动，仅仅保存master node的信息，包括master node的host和ip，但是复制流程没开始。<br> master的host和ip信息配置：<code>redis.conf -&gt; slaveof</code>配置。</p>
</li>
<li><p>slave node内部有个定时任务，每秒检查是否有新的master node要连接和复制，如果发现，就跟master node建立socket网络连接。</p>
</li>
<li>slave node发送ping命令给master node。</li>
<li>口令认证，如果master设置了requirepass，那么salve node必须发送masterauth的口令过去进行认证。</li>
<li>master node第一次执行全量复制，将所有数据发给slave node。</li>
<li>master node后续持续将写命令，异步复制给slave node</li>
</ol>
<h5 id="数据同步相关的核心机制"><a href="#数据同步相关的核心机制" class="headerlink" title="数据同步相关的核心机制"></a>数据同步相关的核心机制</h5><p>指的就是第一次slave连接master的时候，执行的全量复制过程里面的一些细节的机制。</p>
<ol>
<li><p>master和slave都会维护一个offset</p>
<p> master会在自身不断累加offset，slave也会在自身不断累加offset，slave每秒都会上报自己的offset给master，同时master也会保存每个slave的offset。这个倒不是说特定就用在全量复制，主要是master和slave都要知道各自的数据的offset，才能知道互相之间的数据不一致的情况。</p>
</li>
<li><p>backlog</p>
<p> backlog主要是用来做全量复制中断候的增量复制的，master node有一个backlog，默认是1MB大小，master node给slave node复制数据时，也会将数据在backlog中同步写一份。</p>
</li>
<li><p>master run_id介绍</p>
<p> <code>info server</code>可以看到master run_id，如果是根据host+ip定位master node，是不靠谱的，如果master node重启或者数据出现了变化，那么slave node应该根据不同的run_id区分，run_id不同就做全量复制，如果需要不更改run_id重启redis，可以使用<code>redis-cli debug reload</code>命令。</p>
</li>
<li><p>psync</p>
<p> 从节点使用psync从master node进行复制，psync runid offset，master node会根据自身的情况返回响应信息，可能是FULLRESYNC runid offset触发全量复制，可能是CONTINUE触发增量复制。</p>
</li>
</ol>
<h5 id="全量复制"><a href="#全量复制" class="headerlink" title="全量复制"></a>全量复制</h5><p>rdb生成、rdb通过网络拷贝、slave旧数据的清理、slave aof rewrite，其实都很耗费时间，如果复制的数据量在4G~6G之间，那么很可能全量复制时间消耗到1分半到2分钟。</p>
<ol>
<li>master执行bgsave，在本地生成一份rdb快照文件</li>
<li>master node将rdb快照文件发送给salve node，如果rdb复制时间超过60秒（repl-timeout），那么slave node就会认为复制失败，可以适当调节大这个参数。</li>
<li>对于千兆网卡的机器，一般每秒传输100MB，6G文件，很可能超过60s。</li>
<li>master node在生成rdb时，会将所有新的写命令缓存在内存中，在salve node保存了rdb之后，再将新的写命令复制给salve node。</li>
<li>配置解释：<code>client-output-buffer-limit slave 256MB 64MB 60</code>，如果在复制期间，内存缓冲区持续消耗超过64MB，或者一次性超过256MB，那么停止复制，复制失败。</li>
<li>slave node接收到rdb之后，清空自己的旧数据，然后重新加载rdb到自己的内存中，同时基于旧的数据版本对外提供服务。</li>
<li>如果slave node开启了AOF，那么会立即执行<code>BGREWRITEAOF</code>，重写AOF。</li>
</ol>
<h5 id="增量复制"><a href="#增量复制" class="headerlink" title="增量复制"></a>增量复制</h5><ol>
<li>如果全量复制过程中，master-slave网络连接断掉，那么salve重新连接master时，会触发增量复制。</li>
<li>master直接从自己的backlog中获取部分丢失的数据，发送给slave node，默认backlog就是1MB。</li>
<li>msater就是根据slave发送的psync中的offset来从backlog中获取数据的。</li>
</ol>
<h5 id="heartbeat"><a href="#heartbeat" class="headerlink" title="heartbeat"></a>heartbeat</h5><p>主从节点互相都会发送heartbeat信息，master默认每隔10秒发送一次heartbeat，salve node每隔1秒发送一个heartbeat。</p>
<h5 id="异步复制"><a href="#异步复制" class="headerlink" title="异步复制"></a>异步复制</h5><p>master每次接收到写命令之后，现在内部写入数据，然后异步发送给slave node。</p>
<h3 id="Redis读写分离架构实战"><a href="#Redis读写分离架构实战" class="headerlink" title="Redis读写分离架构实战"></a>Redis读写分离架构实战</h3><p>上面的内容都是在铺垫各种redis replication的原理和知识，主从架构，读写分离。接下来就跟随文章进行项目应用实战，搭建一个一主一从的架构，主节点去写，从节点去读。</p>
<p>配置从节点，需要在从节点的<code>redis.conf</code>配置文件中修改<code>slaveof ip port</code>。</p>
<p>我这里配置成<code>slaveof eshop-cache01 6379</code>。</p>
<p>强制读写分离配置：slave节点只读是默认开启的，<code>slave-read-only yes</code>，开启了只读的redis slave node，会拒绝所有的写操作，这样可以强制搭建成读写分离的架构。</p>
<p>如果master有密码，还需要配置<code>masterauth</code>，来授权从节点访问。</p>
<h4 id="读写分离架构的测试"><a href="#读写分离架构的测试" class="headerlink" title="读写分离架构的测试"></a>读写分离架构的测试</h4><p>先启动主节点，eshop-cache01上的redis实例，再启动从节点，eshop-cache02上的redis实例。（eshop-cache01和eshop-cache02是我配置的2台虚拟机。）</p>
<p><strong>!!千万要注意一点，redis的默认配置中，是处于开发模式的，从别的机器是无法访问的，所以要修改<code>bind</code>配置，把它先注释掉吧。</strong></p>
<pre><code>bind 127.0.0.1
</code></pre><p>然后用<code>redis-cli</code>连接从节点，<code>info replication</code>可以看到当前节点集群的配置信息。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; info replication</span><br><span class="line"><span class="comment"># Replication</span></span><br><span class="line">role:slave</span><br><span class="line">master_host:eshop-cache01</span><br><span class="line">master_port:6379</span><br><span class="line">master_link_status:up</span><br><span class="line">master_last_io_seconds_ago:6</span><br><span class="line">master_sync_in_progress:0</span><br><span class="line">slave_repl_offset:84</span><br><span class="line">slave_priority:100</span><br><span class="line">slave_read_only:1</span><br><span class="line">connected_slaves:0</span><br><span class="line">master_replid:081336e1355373b31908914d2a9ac195b0ca2622</span><br><span class="line">master_replid2:0000000000000000000000000000000000000000</span><br><span class="line">master_repl_offset:84</span><br><span class="line">second_repl_offset:-1</span><br><span class="line">repl_backlog_active:1</span><br><span class="line">repl_backlog_size:1048576</span><br><span class="line">repl_backlog_first_byte_offset:1</span><br><span class="line">repl_backlog_histlen:84</span><br></pre></td></tr></table></figure>
<p>连接主节点：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; info replication</span><br><span class="line"><span class="comment"># Replication</span></span><br><span class="line">role:master</span><br><span class="line">connected_slaves:1</span><br><span class="line">slave0:ip=192.168.2.202,port=6379,state=online,offset=714,lag=1</span><br><span class="line">master_replid:081336e1355373b31908914d2a9ac195b0ca2622</span><br><span class="line">master_replid2:0000000000000000000000000000000000000000</span><br><span class="line">master_repl_offset:714</span><br><span class="line">second_repl_offset:-1</span><br><span class="line">repl_backlog_active:1</span><br><span class="line">repl_backlog_size:1048576</span><br><span class="line">repl_backlog_first_byte_offset:1</span><br><span class="line">repl_backlog_histlen:714</span><br></pre></td></tr></table></figure>
<p>在主节点<code>set k1 v2</code>，从节点<code>get k1</code>，马上就能看到结果，数据已经同步过去了。</p>
<h4 id="QPS测试"><a href="#QPS测试" class="headerlink" title="QPS测试"></a>QPS测试</h4><p>如果想要对刚才搭建的Redis集群做一个基准的测试，测一下性能和QPS(query per second)。Redis自己提供了redis-benchmark压测工具，这是最快捷最方便的，当然了，这个工具比较简单，只能用一些简单的操作和场景去压测。</p>
<ol>
<li><p>对redis读写分离架构进行压测，单实例写QPS+单实例读QPS(我是1核1G的虚拟机)</p>
 <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br></pre></td><td class="code"><pre><span class="line">redis-4.0.8/src/redis-benchmark -h localhost</span><br><span class="line">-c &lt;clients&gt;       Number of parallel connections (default 50)</span><br><span class="line">-n &lt;requests&gt;      Total number of requests (default 100000)</span><br><span class="line">-d &lt;size&gt;          Data size of SET/GET value <span class="keyword">in</span> bytes (default 2)</span><br><span class="line">====== PING_INLINE ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.05 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.81% &lt;= 1 milliseconds</span><br><span class="line">99.93% &lt;= 2 milliseconds</span><br><span class="line">100.00% &lt;= 2 milliseconds</span><br><span class="line">95602.30 requests per second</span><br><span class="line"></span><br><span class="line">====== PING_BULK ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.14 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.57% &lt;= 1 milliseconds</span><br><span class="line">99.87% &lt;= 2 milliseconds</span><br><span class="line">99.99% &lt;= 3 milliseconds</span><br><span class="line">100.00% &lt;= 3 milliseconds</span><br><span class="line">87489.06 requests per second</span><br><span class="line"></span><br><span class="line">====== SET ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.23 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">98.93% &lt;= 1 milliseconds</span><br><span class="line">99.75% &lt;= 2 milliseconds</span><br><span class="line">100.00% &lt;= 3 milliseconds</span><br><span class="line">81499.59 requests per second</span><br><span class="line"></span><br><span class="line">====== GET ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.30 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">96.70% &lt;= 1 milliseconds</span><br><span class="line">99.20% &lt;= 2 milliseconds</span><br><span class="line">99.78% &lt;= 3 milliseconds</span><br><span class="line">99.97% &lt;= 4 milliseconds</span><br><span class="line">100.00% &lt;= 5 milliseconds</span><br><span class="line">100.00% &lt;= 5 milliseconds</span><br><span class="line">76863.95 requests per second</span><br><span class="line"></span><br><span class="line">====== INCR ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.51 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">95.39% &lt;= 1 milliseconds</span><br><span class="line">98.90% &lt;= 2 milliseconds</span><br><span class="line">99.73% &lt;= 3 milliseconds</span><br><span class="line">99.93% &lt;= 4 milliseconds</span><br><span class="line">100.00% &lt;= 4 milliseconds</span><br><span class="line">66093.85 requests per second</span><br><span class="line"></span><br><span class="line">====== LPUSH ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.36 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">97.80% &lt;= 1 milliseconds</span><br><span class="line">99.54% &lt;= 2 milliseconds</span><br><span class="line">99.81% &lt;= 3 milliseconds</span><br><span class="line">99.86% &lt;= 4 milliseconds</span><br><span class="line">99.89% &lt;= 5 milliseconds</span><br><span class="line">99.90% &lt;= 6 milliseconds</span><br><span class="line">99.90% &lt;= 8 milliseconds</span><br><span class="line">99.93% &lt;= 9 milliseconds</span><br><span class="line">99.95% &lt;= 10 milliseconds</span><br><span class="line">99.97% &lt;= 11 milliseconds</span><br><span class="line">99.98% &lt;= 12 milliseconds</span><br><span class="line">100.00% &lt;= 12 milliseconds</span><br><span class="line">73260.07 requests per second</span><br><span class="line"></span><br><span class="line">====== RPUSH ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.21 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.79% &lt;= 1 milliseconds</span><br><span class="line">100.00% &lt;= 1 milliseconds</span><br><span class="line">82781.45 requests per second</span><br><span class="line"></span><br><span class="line">====== LPOP ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.24 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.19% &lt;= 1 milliseconds</span><br><span class="line">99.73% &lt;= 2 milliseconds</span><br><span class="line">99.92% &lt;= 3 milliseconds</span><br><span class="line">99.95% &lt;= 4 milliseconds</span><br><span class="line">99.99% &lt;= 5 milliseconds</span><br><span class="line">100.00% &lt;= 5 milliseconds</span><br><span class="line">80645.16 requests per second</span><br><span class="line"></span><br><span class="line">====== RPOP ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.15 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.67% &lt;= 1 milliseconds</span><br><span class="line">99.84% &lt;= 2 milliseconds</span><br><span class="line">99.91% &lt;= 3 milliseconds</span><br><span class="line">99.95% &lt;= 4 milliseconds</span><br><span class="line">99.97% &lt;= 5 milliseconds</span><br><span class="line">100.00% &lt;= 5 milliseconds</span><br><span class="line">86730.27 requests per second</span><br><span class="line"></span><br><span class="line">====== SADD ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.72 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">94.97% &lt;= 1 milliseconds</span><br><span class="line">98.39% &lt;= 2 milliseconds</span><br><span class="line">99.20% &lt;= 3 milliseconds</span><br><span class="line">99.50% &lt;= 4 milliseconds</span><br><span class="line">99.58% &lt;= 5 milliseconds</span><br><span class="line">99.59% &lt;= 6 milliseconds</span><br><span class="line">99.63% &lt;= 7 milliseconds</span><br><span class="line">99.67% &lt;= 8 milliseconds</span><br><span class="line">99.68% &lt;= 9 milliseconds</span><br><span class="line">99.74% &lt;= 10 milliseconds</span><br><span class="line">99.75% &lt;= 11 milliseconds</span><br><span class="line">99.75% &lt;= 12 milliseconds</span><br><span class="line">99.76% &lt;= 13 milliseconds</span><br><span class="line">99.78% &lt;= 14 milliseconds</span><br><span class="line">99.83% &lt;= 15 milliseconds</span><br><span class="line">99.83% &lt;= 16 milliseconds</span><br><span class="line">99.86% &lt;= 17 milliseconds</span><br><span class="line">99.89% &lt;= 23 milliseconds</span><br><span class="line">99.90% &lt;= 24 milliseconds</span><br><span class="line">99.93% &lt;= 25 milliseconds</span><br><span class="line">99.93% &lt;= 27 milliseconds</span><br><span class="line">99.93% &lt;= 31 milliseconds</span><br><span class="line">99.94% &lt;= 33 milliseconds</span><br><span class="line">99.95% &lt;= 41 milliseconds</span><br><span class="line">99.95% &lt;= 42 milliseconds</span><br><span class="line">99.95% &lt;= 43 milliseconds</span><br><span class="line">99.96% &lt;= 44 milliseconds</span><br><span class="line">99.99% &lt;= 46 milliseconds</span><br><span class="line">99.99% &lt;= 49 milliseconds</span><br><span class="line">100.00% &lt;= 52 milliseconds</span><br><span class="line">100.00% &lt;= 55 milliseconds</span><br><span class="line">100.00% &lt;= 56 milliseconds</span><br><span class="line">58038.30 requests per second</span><br><span class="line"></span><br><span class="line">====== HSET ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.26 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.09% &lt;= 1 milliseconds</span><br><span class="line">99.97% &lt;= 2 milliseconds</span><br><span class="line">100.00% &lt;= 2 milliseconds</span><br><span class="line">79617.84 requests per second</span><br><span class="line"></span><br><span class="line">====== SPOP ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.25 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.30% &lt;= 1 milliseconds</span><br><span class="line">99.97% &lt;= 2 milliseconds</span><br><span class="line">100.00% &lt;= 2 milliseconds</span><br><span class="line">80000.00 requests per second</span><br><span class="line"></span><br><span class="line">====== LPUSH (needed to benchmark LRANGE) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.27 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">98.56% &lt;= 1 milliseconds</span><br><span class="line">99.89% &lt;= 2 milliseconds</span><br><span class="line">99.97% &lt;= 3 milliseconds</span><br><span class="line">100.00% &lt;= 4 milliseconds</span><br><span class="line">78616.35 requests per second</span><br><span class="line"></span><br><span class="line">====== LRANGE_100 (first 100 elements) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.17 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">98.44% &lt;= 1 milliseconds</span><br><span class="line">99.83% &lt;= 2 milliseconds</span><br><span class="line">99.96% &lt;= 3 milliseconds</span><br><span class="line">99.99% &lt;= 4 milliseconds</span><br><span class="line">100.00% &lt;= 4 milliseconds</span><br><span class="line">85616.44 requests per second</span><br><span class="line"></span><br><span class="line">====== LRANGE_300 (first 300 elements) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.24 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">97.47% &lt;= 1 milliseconds</span><br><span class="line">99.55% &lt;= 2 milliseconds</span><br><span class="line">99.76% &lt;= 3 milliseconds</span><br><span class="line">99.89% &lt;= 4 milliseconds</span><br><span class="line">99.95% &lt;= 5 milliseconds</span><br><span class="line">99.95% &lt;= 15 milliseconds</span><br><span class="line">99.95% &lt;= 16 milliseconds</span><br><span class="line">99.98% &lt;= 17 milliseconds</span><br><span class="line">100.00% &lt;= 18 milliseconds</span><br><span class="line">100.00% &lt;= 28 milliseconds</span><br><span class="line">100.00% &lt;= 28 milliseconds</span><br><span class="line">80906.15 requests per second</span><br><span class="line"></span><br><span class="line">====== LRANGE_500 (first 450 elements) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.16 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.01% &lt;= 1 milliseconds</span><br><span class="line">99.78% &lt;= 2 milliseconds</span><br><span class="line">99.88% &lt;= 3 milliseconds</span><br><span class="line">99.99% &lt;= 4 milliseconds</span><br><span class="line">100.00% &lt;= 4 milliseconds</span><br><span class="line">86355.79 requests per second</span><br><span class="line"></span><br><span class="line">====== LRANGE_600 (first 600 elements) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.08 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">99.17% &lt;= 1 milliseconds</span><br><span class="line">99.82% &lt;= 2 milliseconds</span><br><span class="line">99.90% &lt;= 3 milliseconds</span><br><span class="line">99.96% &lt;= 4 milliseconds</span><br><span class="line">99.98% &lt;= 5 milliseconds</span><br><span class="line">100.00% &lt;= 8 milliseconds</span><br><span class="line">100.00% &lt;= 8 milliseconds</span><br><span class="line">92250.92 requests per second</span><br><span class="line"></span><br><span class="line">====== MSET (10 keys) ======</span><br><span class="line">  100000 requests completed <span class="keyword">in</span> 1.28 seconds</span><br><span class="line">  50 parallel clients</span><br><span class="line">  3 bytes payload</span><br><span class="line">  keep alive: 1</span><br><span class="line"></span><br><span class="line">96.11% &lt;= 1 milliseconds</span><br><span class="line">98.95% &lt;= 2 milliseconds</span><br><span class="line">99.49% &lt;= 3 milliseconds</span><br><span class="line">99.70% &lt;= 4 milliseconds</span><br><span class="line">99.76% &lt;= 5 milliseconds</span><br><span class="line">99.86% &lt;= 6 milliseconds</span><br><span class="line">99.94% &lt;= 7 milliseconds</span><br><span class="line">99.96% &lt;= 8 milliseconds</span><br><span class="line">99.98% &lt;= 10 milliseconds</span><br><span class="line">100.00% &lt;= 10 milliseconds</span><br><span class="line">78369.91 requests per second</span><br></pre></td></tr></table></figure>
<p> 到了环境中，QPS就不一定能有这么高了，因为网络本身就有开销，还有QPS两大杀手，一个是lrange操作，还有就是如果value很大，也比较费时。</p>
</li>
<li><p>水平扩容redis读节点，提升度吞吐量</p>
<p> 再在其他服务器上搭建redis从节点，单个从节点读请QPS在5万左右，两个redis从节点，所有的读请求到两台机器上去，承载整个集群读QPS在10万+。</p>
</li>
</ol>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/redis/" rel="tag"># redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/12/cache03/" rel="next" title="高可用缓存架构实战3-Redis高可用集群实战">
                <i class="fa fa-chevron-left"></i> 高可用缓存架构实战3-Redis高可用集群实战
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/18/cache04/" rel="prev" title="高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案">
                高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis企业应用实战"><span class="nav-number">1.</span> <span class="nav-text">Redis企业应用实战</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#企业级的持久化的配置策略"><span class="nav-number">1.1.</span> <span class="nav-text">企业级的持久化的配置策略</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#企业级的数据备份方案"><span class="nav-number">1.2.</span> <span class="nav-text">企业级的数据备份方案</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#每小时copy一次备份，删除48小时前的数据"><span class="nav-number">1.2.1.</span> <span class="nav-text">每小时copy一次备份，删除48小时前的数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#每天copy一次备份"><span class="nav-number">1.2.2.</span> <span class="nav-text">每天copy一次备份</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据恢复方案"><span class="nav-number">1.2.3.</span> <span class="nav-text">数据恢复方案</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何通过读写分离来承载读请求QPS超过10万-？"><span class="nav-number">1.3.</span> <span class="nav-text">如何通过读写分离来承载读请求QPS超过10万+？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#redis高并发跟整个系统的高并发之间的关系"><span class="nav-number">1.3.1.</span> <span class="nav-text">redis高并发跟整个系统的高并发之间的关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#redis不能支撑高并发的瓶颈在哪里？"><span class="nav-number">1.3.2.</span> <span class="nav-text">redis不能支撑高并发的瓶颈在哪里？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如果redis要支撑超过10万-的并发，那应该怎么做？"><span class="nav-number">1.3.3.</span> <span class="nav-text">如果redis要支撑超过10万+的并发，那应该怎么做？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Redis-Replication"><span class="nav-number">1.3.4.</span> <span class="nav-text">Redis Replication</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis-Replication的核心机制"><span class="nav-number">1.3.4.1.</span> <span class="nav-text">Redis Replication的核心机制</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#master持久化对于主从架构的安全保障的意义"><span class="nav-number">1.3.4.1.1.</span> <span class="nav-text">master持久化对于主从架构的安全保障的意义</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主从架构的核心原理"><span class="nav-number">1.3.4.1.2.</span> <span class="nav-text">主从架构的核心原理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主从复制的断点续传"><span class="nav-number">1.3.4.1.3.</span> <span class="nav-text">主从复制的断点续传</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#无磁盘化复制"><span class="nav-number">1.3.4.1.4.</span> <span class="nav-text">无磁盘化复制</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#过期key处理"><span class="nav-number">1.3.4.1.5.</span> <span class="nav-text">过期key处理</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#深入理解复制机制"><span class="nav-number">1.3.4.2.</span> <span class="nav-text">深入理解复制机制</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#复制的完整流程"><span class="nav-number">1.3.4.2.1.</span> <span class="nav-text">复制的完整流程</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#数据同步相关的核心机制"><span class="nav-number">1.3.4.2.2.</span> <span class="nav-text">数据同步相关的核心机制</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#全量复制"><span class="nav-number">1.3.4.2.3.</span> <span class="nav-text">全量复制</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#增量复制"><span class="nav-number">1.3.4.2.4.</span> <span class="nav-text">增量复制</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#heartbeat"><span class="nav-number">1.3.4.2.5.</span> <span class="nav-text">heartbeat</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#异步复制"><span class="nav-number">1.3.4.2.6.</span> <span class="nav-text">异步复制</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Redis读写分离架构实战"><span class="nav-number">1.3.5.</span> <span class="nav-text">Redis读写分离架构实战</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#读写分离架构的测试"><span class="nav-number">1.3.5.1.</span> <span class="nav-text">读写分离架构的测试</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#QPS测试"><span class="nav-number">1.3.5.2.</span> <span class="nav-text">QPS测试</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
